package com.his_voice.voice.server;

import com.his_voice.voice.utils.WebSocketMapUtils;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{apicode}")
public class MyWebSocketServer {
    private Logger logger = LoggerFactory.getLogger(MyWebSocketServer.class);
    private Session session;


    private WebSocketClient client;
    private  String apiCode;

    private  static  int onlineCount = 0;

    private final  String url = "wss://rtasr.xfyun.cn/v1/ws";

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     * 在外部可以获取此连接的所有websocket对象，并能对其触发消息发送功能，我们的定时发送核心功能的实现在与此变量
     */
    private static CopyOnWriteArraySet<MyWebSocketServer> websocketServer = new CopyOnWriteArraySet<MyWebSocketServer>();

    /**
     * 建立连接
     *
     * @param apiCode
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam(value = "apiCode") String apiCode, Session session) throws Exception {
        this.session = session;
        System.out.println("建立链接！");
        System.out.println(apiCode);
        addOnlineCount();
        websocketServer.add(this);
        //连接调用第三方服务
//        client = client.getClient("ws://192.168.0.109:8013/websocket");
        client = WebSocketMapUtils.getClient(this.session.getId());
    }
    @OnClose
    public void OnClose() {
        System.out.println("关闭链接！");
        websocketServer.remove(this);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.info("发生错误");
        websocketServer.remove(this);
    }


    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的音频数据
     */
    @OnMessage
    public void onMessage(@PathParam(value = "apiCode") String apiCode, byte[] message) {
        log.info("音频数据报文:" + message);
        try {
            //在线
            client.send(message);
            log.info("发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("发送失败！"+ e.getMessage());
//            ExceptionLog.isSuccess(apiCode, null,null);
        }
    }
    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的字符数据
     */
    @OnMessage
    public void onMessage(@PathParam(value = "apiCode") String apiCode, String message) {
        log.info("字符数据报文:" + message);
        try {
            //在线
            client.send(message);


            sendMessage(message);
//            ExceptionLog.isSuccess(apiCode, message,null);
        } catch (Exception e) {
            //离线
//            isconnct(apiCode);
//            client.send(message);
//            ExceptionLog.isSuccess(apiCode, message,null);
        }
    }

    /**
     * 实现服务器主动推送
     *
     * @param message
     */
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocketServer.onlineCount--;
    }

    public static CopyOnWriteArraySet<MyWebSocketServer> getWebSocketSet() {
        return websocketServer;
    }

    public static void setWebSocketSet(CopyOnWriteArraySet<MyWebSocketServer> webSocketSet) {
        MyWebSocketServer.websocketServer = webSocketSet;
    }

}
